Dajaxice.setup({
	'default_exception_callback' : function() {
		alert('Error! Something happens!!!');
	}
});

//start idle sensor
startIdleSensor();
//
var is_fresh = true;

// this function takes care of the received text from server side
function update(data) {
	// first add to history
	if (!is_fresh) {
		ui = $('#usrInput').val();
		$('#history').prepend(
				'<p class="even"><b>Talker:</b>' + $('#reply').html() + '</p>');
		$('#history').prepend('<p class="odd"><b>User:</b>' + ui + '</p>');
	}

	$('#reply').html('&nbsp');
	$.each(data.message, add_reply);

	$('#usrInput').autocomplete( "close" );
	$('#usrInput').val('');
	is_fresh = false;
};

function add_reply(index, val) {
	paragraphs = val.split('\n')
	$.each(paragraphs, function(i, v) {
		$('#reply').append(v + "<br/>");
	});
};

// ------------------------------------------------------------------
// Autocomplete part adapted from autocomplete multiple-remote Demo
// ------------------------------------------------------------------

function split(val) {
	return val.split(/,\s*/);
};

function extractLast(term) {
	return split(term).pop();
};

$(function() {
	$("#usrInput")// don't navigate away from the field on tab when selecting
					// an item
	.bind(
			"keydown",function(event) {
				if (event.keyCode === $.ui.keyCode.TAB
						&& $(this).data("autocomplete").menu.active) {
					event.preventDefault();
				}
				else if (event.keyCode === $.ui.keyCode.ENTER 
						&& !($(this).data("autocomplete").menu.active)) {
					Dajaxice.chat.update(update, {'text' : $('#usrInput').val()});
				}
			})
	    .autocomplete({
		source : function(request, response) {
			Dajaxice.chat.suggestion_list(response, {
				"term" : extractLast(request.term)
			});
		},
		search : function() {
			// custom minLength
			var term = extractLast(this.value);
			if (term.length < 2) {
				return false;
			}
		},
		focus : function() {
			// prevent value inserted on focus
			return false;
		},
		select : function(event, ui) {
			var terms = split(this.value);
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push(ui.item.value);
			// add placeholder to get the comma-and-space at the end
			terms.push("");
			this.value = terms.join(", ");
			return false;
		}
	});
});

$( document ).ready( function() {
	Dajaxice.chat.update(update, {'text' : $('#usrInput').val()});
})

$( document ).unload( function () {
	stopIdleSensor();
	Dajaxice.chat.before_leave(function () {},{})
})
